//
//  RealatorViewAppDelegate.m
//  RealatorView
//
//  Created by Ricky Jones on 1/20/09.
//  Copyright Vaporsoftware 2009. All rights reserved.
//

#import "RealatorViewAppDelegate.h"
#import "Location.h"
#import "LocationsViewController.h"
#import "LocationViewController.h"

@implementation RealatorViewAppDelegate

@synthesize window;
@synthesize viewController;
@synthesize NavigationController = _navController;

- (void) ShowLocation:(Location*)locationToShow
{
	LocationViewController* v = [[LocationViewController alloc]initWithNibName:@"ViewLocation" bundle:nil];
	[v setCurrentLocation:locationToShow];
	[self ChangeView:v];
}



- (void) ChangeView:(UIViewController*) controller
{	
//	[UIView beginAnimations:nil context:NULL];
//	[UIView setAnimationDuration:2.0];
//	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:window cache:YES];
//	[viewController.view removeFromSuperview];
//	[self.window addSubview:[controller view]];
//	[UIView commitAnimations];
//[_navController popViewControllerAnimated:true];
	[_navController pushViewController:controller animated: true];
//	[self setViewController:controller];
///	[controller release];
	
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {  
	[self copyDatabaseIfNeeded];
//	[window addSubview:viewController.view];
	LocationsViewController * view = [[[LocationsViewController alloc] initWithNibName:@"ViewLocations" bundle:nil] autorelease];
	 _navController = [[UINavigationController alloc] initWithRootViewController:view];
	[window addSubview:[_navController view]];
	// Override point for customization after application launch
    [window makeKeyAndVisible];
}


- (NSString *) getDBPath {
	
	//Search for standard documents using NSSearchPathForDirectoriesInDomains
	//First Param = Searching the documents directory
	//Second Param = Searching the Users directory and not the System
	//Expand any tildes and identify home directories.
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
	NSString *documentsDir = [paths objectAtIndex:0];
	return [documentsDir stringByAppendingPathComponent:@"RealtorView.sqlite"];
}


- (void) copyDatabaseIfNeeded {
	
	
	//Using NSFileManager we can perform many file system operations.
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;
	NSString *dbPath = [self getDBPath];
	BOOL success = [fileManager fileExistsAtPath:dbPath];
	
	if(success) 
	{
		[fileManager removeItemAtPath: dbPath error:&error];
	}
		NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"RealtorView.sqlite"];

		success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
		
		if (!success)
			NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
	//}
}

	
	
- (void)dealloc {
    [window release];
    [super dealloc];
}


@end
